const app = getApp()
//获得全局js变量
var util = require('../../../utils/util.js');
Page({
    data: {
        projectName: '',
        projectDays: '',
        clientName: '',
        clientPhone:'',
        amount: '',
        description: '',
        status:0,
        categoryOptions: ['未开始', '进行中', '已完成', '已取消'],
        categoryIndex: 0,
        startDate: '',
        endDate: '',
        teamMembers: [],
        
        // 弹窗相关
        showModal: false,
        newMember: {
            name: '',
            role: '',
            ratio: ''
        },
        roleOptions: ['项目经理', '技术主管', '销售经理', '客户经理', '技术支持', '其他'],
        roleIndex: 0,
        projectId:''
    },
    
    onLoad: function(options) {
        this.setData({
            projectId:options.id
        });
        // 设置默认日期为今天
        const today = this.formatDate(new Date());
        
        // 设置默认结束日期为30天后
        const endDate = new Date();
        endDate.setDate(endDate.getDate() + 30);
        
        this.setData({
            startDate: today,
            endDate: this.formatDate(endDate)
        });
        this.getProjectCate();
    },
    getProjectCate:function(){
        var that=this;
        util.httpRrquest(app.data.rooturl + 'system/getProjectCate', 'GET')
        .then(function (response) {
            if (response.data.code == 1) {
                that.setData({
                    categoryOptions: response.data.data
                });
                that.getProjectInfo();
            }
        }, function (error) {
            console.log(error);
        });
    },
    getProjectInfo:function(){
        var that=this;
        var projectId=this.data.projectId;
        util.httpRrquest(app.data.rooturl +'user/getProjectInfo?projectId='+projectId, 'GET') 
        .then(function (response) {
            var data = response.data.data;
            if (response.data.code == 1) {
                that.setData({
                    projectName: data.name,
                    projectDays: data.days,
                    clientName: data.customerName,
                    clientPhone:data.customerPhone,
                    amount: data.allMoney,
                    description: data.content,
                    status: data.status,
                    categoryIndex: data.category,
                    startDate: data.startDate,
                    endDate: data.endDate
                });
            }
        }, function (error) {
            console.log(error);
        });
    },
    // 格式化日期为YYYY-MM-DD
    formatDate: function(date) {
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        return `${year}-${month}-${day}`;
    },
    
    // 输入项目名称
    inputProjectName: function(e) {
        this.setData({
            projectName: e.detail.value
        });
    },
    // 输入项目周期
    inputProjectDays: function(e) {
        this.setData({
            projectDays: e.detail.value
        });
    },
    // 输入客户名称
    inputClientName: function(e) {
        this.setData({
            clientName: e.detail.value
        });
    },
    inputClientPhone:function(e){
        this.setData({
            clientPhone: e.detail.value
        });
    },
    // 输入项目金额
    inputAmount: function(e) {
        this.setData({
            amount: e.detail.value
        });
    },
    
    // 输入项目描述
    inputDescription: function(e) {
        this.setData({
            description: e.detail.value
        });
    },
    
    // 选择项目类别
    statusChange: function(e) {
        this.setData({
            categoryIndex: e.detail.value
        });
    },
    
    // 选择开始日期
    startDateChange: function(e) {
        this.setData({
            startDate: e.detail.value
        });
    },
    
    // 选择结束日期
    endDateChange: function(e) {
        this.setData({
            endDate: e.detail.value
        });
    },
    
    // 显示添加成员弹窗
    showAddMember: function() {
        this.setData({
            showModal: true,
            newMember: {
                name: '',
                role: this.data.roleOptions[0],
                ratio: ''
            },
            roleIndex: 0
        });
    },
    
    // 隐藏弹窗
    hideModal: function() {
        this.setData({
            showModal: false
        });
    },
    
    // 输入成员姓名
    inputMemberName: function(e) {
        this.setData({
            'newMember.name': e.detail.value
        });
    },
    
    // 选择成员角色
    roleChange: function(e) {
        this.setData({
            roleIndex: e.detail.value,
            'newMember.role': this.data.roleOptions[e.detail.value]
        });
    },
    
    // 输入提成比例
    inputMemberRatio: function(e) {
        this.setData({
            'newMember.ratio': e.detail.value
        });
    },
    
    // 添加团队成员
    addMember: function() {
        const { newMember, teamMembers } = this.data;
        
        if (!newMember.name) {
            wx.showToast({
                title: '请输入成员姓名',
                icon: 'none'
            });
            return;
        }
        
        if (!newMember.ratio) {
            wx.showToast({
                title: '请输入提成比例',
                icon: 'none'
            });
            return;
        }
        
        // 验证提成比例是否为数字且在0-100之间
        const ratio = parseFloat(newMember.ratio);
        if (isNaN(ratio) || ratio <= 0 || ratio > 100) {
            wx.showToast({
                title: '提成比例应在0-100之间',
                icon: 'none'
            });
            return;
        }
        
        // 计算当前总提成比例
        const currentTotalRatio = teamMembers.reduce((sum, member) => sum + parseFloat(member.ratio), 0);
        
        // 验证总提成比例不超过100%
        if (currentTotalRatio + ratio > 100) {
            wx.showToast({
                title: '总提成比例不能超过100%',
                icon: 'none'
            });
            return;
        }
        
        // 添加新成员
        const newTeamMembers = [...teamMembers, {
            id: Date.now(),  // 使用时间戳作为临时ID
            name: newMember.name,
            role: newMember.role,
            ratio: ratio
        }];
        
        this.setData({
            teamMembers: newTeamMembers,
            showModal: false
        });
    },
    
    // 移除团队成员
    removeMember: function(e) {
        const memberId = e.currentTarget.dataset.id;
        const newTeamMembers = this.data.teamMembers.filter(member => member.id !== memberId);
        
        this.setData({
            teamMembers: newTeamMembers
        });
    },
    
    // 取消创建项目
    cancelCreate: function() {
        wx.showModal({
            title: '提示',
            content: '确定要取消修改项目吗？',
            success: (res) => {
                if (res.confirm) {
                    wx.navigateBack();
                }
            }
        });
    },
    
    // 提交项目
    submitProject: function() {
        const { 
            projectName, 
            projectDays,
            clientPhone,
            clientName, 
            amount, 
            description, 
            categoryOptions, 
            categoryIndex, 
            startDate, 
            endDate, 
            teamMembers 
        } = this.data;
        
        // 表单验证
        if (!projectName) {
            wx.showToast({
                title: '请输入项目名称',
                icon: 'none'
            });
            return;
        }
        
        if (!clientName) {
            wx.showToast({
                title: '请输入客户名称',
                icon: 'none'
            });
            return;
        }
        
        if (!amount) {
            wx.showToast({
                title: '请输入项目金额',
                icon: 'none'
            });
            return;
        }
        
        // 验证金额是否为数字且大于0
        const amountNum = parseFloat(amount);
        if (isNaN(amountNum) || amountNum <= 0) {
            wx.showToast({
                title: '请输入有效的项目金额',
                icon: 'none'
            });
            return;
        }
        
        // // 验证团队成员
        // if (teamMembers.length === 0) {
        //     wx.showToast({
        //         title: '请添加至少一名团队成员',
        //         icon: 'none'
        //     });
        //     return;
        // }
        
        // // 验证总提成比例是否为100%
        // const totalRatio = teamMembers.reduce((sum, member) => sum + parseFloat(member.ratio), 0);
        // if (totalRatio !== 100) {
        //     wx.showToast({
        //         title: '团队总提成比例应为100%',
        //         icon: 'none'
        //     });
        //     return;
        // }
        
        // 构建项目数据
        const projectData = {
            id:this.data.projectId,
            name: projectName,
            projectDays: projectDays,
            clientName: clientName,
            clientPhone: clientPhone,
            amount: amountNum,
            description: description,
            category: categoryOptions[categoryIndex],
            startDate: startDate,
            endDate: endDate,
            teamMembers: teamMembers,
            createTime: new Date().toISOString()
        };
        util.httpRrquest(app.data.rooturl + 'user/addProject', 'POST',projectData)
        .then(function (response) {
            if (response.data.code == 1) {
                wx.showModal({
                    title: '申请提交成功',
                    content: '您的项目申请已提交，我们将在1-3个工作日内审核，请留意审核状态。',
                    showCancel: false,
                    success: () => {
                        wx.navigateBack();
                    }
                });	
            }
        }, function (error) {
            console.log(error);
        });
    }
})